package UserInterfase;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import core.IvoCheckers;
import UserInterfase.SimpleBoard;
import UserInterfase.UITools;
import java.awt.Color;

/** The main graphical user interface for ivoCheckers.  This particular GUI
 * is a quick and dirty GUI used only for overall testing and for the first
 * few stable releases.  No don't expect any images or anything like that 
 * because that is what the GraphicalUI does.
 */
public class SimpleGUI extends JFrame implements UserInterface, ActionListener {

	/** The game board (one crazy game board..). */
	private static SimpleBoard gameBoard;

    public static Color startColorLight = Color.GREEN;
    public static Color endColorLight = Color.RED;
    public static Color startColorDark = Color.BLUE;
    public static Color endColorDark = Color.BLACK;


	/** The menu bar for the main window. */
	private JMenuBar menuBar;

	/** The menu that deals with game handling. */
	private JMenu gameMenu;
    private static final String strGameMenu = "Games";

    /** The menu that change color of light pieces */
    private JMenu lightColor;
    private static final String strLightMenu = "Light Color";

    /** The menu that change color of dark pieces */
    private JMenu darkColor;
    private static final String strDarkMenu = "Dark Color";


	/** The menu that handles the help features. */
	private JMenu helpMenu;
        private static final String strHelpMenu = "Help";


	/** The menu item that starts a new game. */
	private JMenuItem newLocalGame;
    private static final String strLocalGame = "New Local Game";

    /** The menu item that starts a new game. */
	private JMenuItem newNetGame;
    private static final String strNetGame = "New Network Game";

    /** The menu item that starts a new game. */
	private JMenuItem findGame;
    private static final String strFindGame = "Find Game";

    /** The menu item that exits the program. */
	private JMenuItem exitProg;
    private static final String strExit= "Exit";

	/** The menu item that shows the credits frame. */
	private JMenuItem credits;
    private static final String strCredits= "Credits";
        
    private JMenuItem rules;
    private static final String strRules = "Rules";

    private JMenuItem darkBlue;
    private JMenuItem darkRed;
    private JMenuItem darkGreen;
    private JMenuItem darkYellow;
    private JMenuItem darkGrey;
    private JMenuItem lightBlue;
    private JMenuItem lightRed;
    private JMenuItem lightGreen;
    private JMenuItem lightYellow;
    private JMenuItem lightGrey;

        
        public static StartGame windowStartGame;
        
        public static SimpleBoard getBoard()
        {
            return gameBoard;
        }
        
	/** Initiates parts of the main windows and any other forms. */
	public void initUI() {
		// Initializes the frame itself. //
		this.setTitle("Ivo Checkers!");
		this.setSize(420, 480);
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                
                addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosed(java.awt.event.WindowEvent evt) {
                        formWindowClosed(evt);
                    }
                });
                
                
		// Center align the window on the screen.
		Point screenCenter = UITools.getCenterOfScreen();
		Point adjust = UITools.getAdjustToPoint(this, screenCenter);
		this.setLocation(adjust);

		/* Creates the main menu. */
		menuBar = new JMenuBar();
		gameMenu = new JMenu(strGameMenu);
        lightColor = new JMenu(strLightMenu);
        darkColor = new JMenu(strDarkMenu);
		helpMenu = new JMenu(strHelpMenu);

        darkBlue = new JMenuItem("DARK BLUE");
        darkRed = new JMenuItem("DARK RED");
        darkGreen = new JMenuItem("DARK GREEN");
        darkYellow = new JMenuItem("DARK YELLOW");
        darkGrey = new JMenuItem("DARK GREY");
        lightBlue = new JMenuItem("LIGHT BLUE");
        lightRed = new JMenuItem("LIGHT RED");
        lightGreen = new JMenuItem("LIGHT GREEN");
        lightYellow = new JMenuItem("LIGHT YELLOW");
        lightGrey = new JMenuItem("LIGHT GREY");



		newLocalGame = new JMenuItem(strLocalGame);
        newNetGame = new JMenuItem(strNetGame);
        findGame = new JMenuItem(strFindGame);
		exitProg = new JMenuItem(strExit);
		credits = new JMenuItem(strCredits);
        rules = new JMenuItem(strRules);


		/* Create action listeners, etc. to capture GUI events. */
		newLocalGame.addActionListener(this);
        newNetGame.addActionListener(this);
        findGame.addActionListener(this);
		exitProg.addActionListener(this);
		credits.addActionListener(this);
        rules.addActionListener(this);

        //for colors

        darkBlue.addActionListener(this);
        darkRed.addActionListener(this);
        darkGreen.addActionListener(this);
        darkYellow.addActionListener(this);
        darkGrey.addActionListener(this);
        lightBlue.addActionListener(this);
        lightRed.addActionListener(this);
        lightGreen.addActionListener(this);
        lightYellow.addActionListener(this);
        lightGrey.addActionListener(this);


            addComponentListener(new java.awt.event.ComponentAdapter() {
                public void componentResized(java.awt.event.ComponentEvent evt) {
                    formComponentResized(evt);
                }
            });

		/* Adds all the menu items together. */
		gameMenu.add(newLocalGame);
        gameMenu.add(newNetGame);
        gameMenu.add(findGame);
		gameMenu.add(exitProg);
        helpMenu.add(rules);
        helpMenu.add(credits);

        darkColor.add(darkBlue);
        darkColor.add(darkRed);
        darkColor.add(darkGreen);
        darkColor.add(darkYellow);
        darkColor.add(darkGrey);
        lightColor.add(lightBlue);
        lightColor.add(lightRed);
        lightColor.add(lightGreen);
        lightColor.add(lightYellow);
        lightColor.add(lightGrey);

		menuBar.add(gameMenu);
        menuBar.add(lightColor);
        menuBar.add(darkColor);
		menuBar.add(helpMenu);
		this.setJMenuBar(menuBar);
	}

	/** The event of exiting for the UI. 
	 * 
	 * TODO: 
	 * - ask the user if they are sure they want to exit.
	 * - blocks if game is in progress. 
	 */
	public void exitUI() {
		IvoCheckers.quit();
	}

	/** Starts up the initial screen. */
	public void displayUI() {
		this.show();
		clearBoard();
	}

	/** Clears the board of all pieces. */
	public void clearBoard() {
		/* Deals with the background image. */
		gameBoard = new SimpleBoard(this.getContentPane());
		displayBoard();
	}

	/** Places the checker pieces in their appropriate locations.  Done when a 
	 * game is started or loaded from memory.  
	 * 
	 * Requires: clearBoard() to be executed first.
	 */
	public void placePieces() {
		gameBoard.placePieces();
		// Show all your hard work.
		displayBoard();
	}

	/** Occurs when a single piece's position is changed.
	 * This occurs at the end of a move.
	 */
	public void movePiece() {
	}

	/** Ends the current game.  Basically shows a message on who won,
	 * and that is it.
	 */
	public void endGame() {
		
            if (!SimpleBoard.getIsNetGame())
            {
                String message = "";
		if (IvoCheckers.getGame().gameHasBeenWon() == 1) {
			message = "Dark player wins!";
		} else if (IvoCheckers.getGame().gameHasBeenWon() == 2) {
			message = "Light player wins!";
		} else {
			message = "ERROR!";
		}

		JOptionPane.showMessageDialog(
			null,
			message,
			"Game Over!",
			JOptionPane.INFORMATION_MESSAGE);
                
            }
	}

	/** Invoked when an action occurs. 
	 * @param event The GUI action that was performed.
	 */
	public void actionPerformed(ActionEvent event) {

            // Execute the events.
            if (strExit.equals(event.getActionCommand())) {
                setVisible(false);
                dispose();
            } else if (strRules.equals(event.getActionCommand())) {
                String message = 
                        "Шашките се играят на стандартна шахматна дъска с 64 полета.\n" +
                        "Всеки играч започва играта с 12 фигури - шашки, разположени на три реда от страната на състезателя\n" +
                        "Целта на играта е да се вземат всички противникови фигури или да се постигне позиция,\n" +
                        "в която противникът да не може да мести.\n" +
                        "Шашките могат да се движат по едно поле диагонално напред, назад не могат.\n" +
                        "Ако шашката стигне до срещуположния край на дъската (последния ред), \n" +
                        "тя се превръща в цар, който добавя и заден ход към своите способности.\n" +
                        "Ако шашка стои до противникова фигура (посока напред) и полето след нея е празно, \n" +
                        "то играчът е длъжен да вземе противниковата фигура, като я прескочи и я премахне от дъската.\n" +
                        "Ако след прескачането е възможно да се прескочи още една противникова фигура, то играчът е длъжен да вземе и нея.\n" +
                        "Това означава, че могат да се вземат няколко фигури с един ход.\n" +
                        "Същото правило се прилага и за царя, с една разлика - царят може да взема и назад.\n" +
                        "Могат да се прескачат само противникови фигури, собствените - не.\n" +
                        "Шашката прескочила противникова шашка и превърнала се в цар (достигайки последния ред на дъската), \n" +
                        "не може да продължи да скача като цар в рамките на този ход, дори да е възможно.\n" +
                        "При произвеждането на цар, ходът ВИНАГИ свършва!\n\n" +
                        "                 УСПЕХ!";
                JOptionPane.showMessageDialog(
			null,
			message,
			"Правила на играта:",
			JOptionPane.INFORMATION_MESSAGE);
            }
            else if ("DARK BLUE".equals(event.getActionCommand()) || "DARK RED".equals(event.getActionCommand()) ||
                    "DARK GREEN".equals(event.getActionCommand()) || "DARK YELLOW".equals(event.getActionCommand()) ||
                    "DARK GREY".equals(event.getActionCommand()))
            {

                changePieceColor(event.getActionCommand().substring(5), true);
                clearBoard();
                placePieces();
            }
            else if ("LIGHT BLUE".equals(event.getActionCommand()) || "LIGHT RED".equals(event.getActionCommand()) ||
                    "LIGHT GREEN".equals(event.getActionCommand()) || "LIGHT YELLOW".equals(event.getActionCommand()) ||
                    "LIGHT GREY".equals(event.getActionCommand()))
            {
                changePieceColor(event.getActionCommand().substring(6), false);
                clearBoard();
                placePieces();
            }
            else if (strCredits.equals(event.getActionCommand())) {
                    this.showCredits();
            } else if (strLocalGame.equals(event.getActionCommand())) {
                    IvoCheckers.startNewGame();
                    JOptionPane.showMessageDialog(
                        null,
                        "Двамата играчи играят на една дъска!",
                        "Info",
			JOptionPane.INFORMATION_MESSAGE);
            }
            else if (strNetGame.equals(event.getActionCommand())) {
                windowStartGame = new StartGame();
                windowStartGame.initComponents(this.getX() + 10, this.getY() + 10);

            } else if (strFindGame.equals(event.getActionCommand())) {
                    IvoCheckers.findGame();
            }
	}

    private void formComponentResized(java.awt.event.ComponentEvent evt) {
//        gameBoard.playerPressed(6, 6);
//        gameBoard.playerReleased(5, 5);
//        clearBoard();
//        placePieces();
        
        this.setSize(420, 480);
    }
    
    private void formWindowClosed(java.awt.event.WindowEvent evt) {
        exitUI();
    }
	/** Shows a form that displays the credits for the ivoCheckers project.  Here
	* all the names of the great people who worked are displayed along with their
	* achievements.
	*/
	private void showCredits() {
		/* Set up the entire logo and credits widget. */
                
		JLabel title =
			new JLabel("About: IvoCheckers-2009");
		JLabel version =
			new JLabel("Version: " + IvoCheckers.IVOCHECKERS_VERSION);
		JLabel credits = new JLabel("");

		/* Deal with the panel container. */
		JPanel splash = new JPanel();
		splash.setLayout(new BoxLayout(splash, BoxLayout.Y_AXIS));
		
		splash.add(title);
		splash.add(version);
		splash.add(credits);

		JOptionPane.showMessageDialog(
			this,
			splash,
			"Credits",
			JOptionPane.PLAIN_MESSAGE);
	}

	/** Displays the final board image after all the processing is done.
	 * Requires: any processing to be done first and tempImage != null
	 */
	private void displayBoard() {
		/* Creates the board game using doublebuffering. */
		this.getContentPane().removeAll();
		this.getContentPane().add(gameBoard);
		this.repaint();
	}

    public void changePieceColor(String new_color, boolean isDark)
    {
        Color start = null, end = null;
        if (isDark)
        {
            SimpleGUI.startColorDark = Color.BLACK;
        }
        else
        {
            SimpleGUI.startColorLight = Color.WHITE;
        }
        if (new_color.equals("BLUE"))
        {
            if (isDark)
                SimpleGUI.endColorDark = Color.BLUE;
            else
                SimpleGUI.endColorLight = Color.BLUE;
        }
        else if (new_color.equals("RED"))
             {
                if (isDark)
                    SimpleGUI.endColorDark = Color.RED;
                else
                    SimpleGUI.endColorLight = Color.RED;
             }
        else if (new_color.equals("GREEN"))
             {
                if (isDark)
                    SimpleGUI.endColorDark = Color.GREEN;
                else
                    SimpleGUI.endColorLight = Color.GREEN;
             }
        else if (new_color.equals("YELLOW"))
             {
                if (isDark)
                    SimpleGUI.endColorDark = Color.YELLOW;
                else
                    SimpleGUI.endColorLight = Color.YELLOW;
            }
        else if (new_color.equals("GRAY"))
             {
                if (isDark)
                    SimpleGUI.endColorDark = Color.GRAY;
                else
                    SimpleGUI.endColorLight = Color.GRAY;
            }
        else
        {
            if (isDark)
                SimpleGUI.endColorDark = Color.CYAN;
            else
                SimpleGUI.endColorLight = Color.MAGENTA;
        }


    }

}
